const Router = require('koa-router');
const axios = require('axios');
const readline = require('readline');

const router = new Router();

// 流式输出
async function proxyStream(ctx, apiKey, difyBody) {
  try {
    const response = await axios.post(
      'http://g38c8662.natappfree.cc/v1/chat-messages',
      difyBody,
      {
        headers: {
          'Authorization': apiKey,
          'Content-Type': 'application/json',
          'Accept': 'text/event-stream'
        },
        responseType: 'stream',
        timeout: 0
      }
    );

    ctx.set({
      'Content-Type': 'text/event-stream; charset=utf-8',
      'Cache-Control': 'no-cache',
      'Connection': 'keep-alive',
      'Transfer-Encoding': 'chunked'
    });

    ctx.status = 200;

    const rl = readline.createInterface({
      input: response.data,
      crlfDelay: Infinity
    });

    ctx.req.on('close', () => {
      response.data.destroy();
      rl.close();
    });

    for await (const line of rl) {
      if (line.trim().startsWith('event: ping')) continue;
      ctx.res.write(line + '\n');
    }
    ctx.res.end();

  } catch (err) {
    console.error('API 错误:', err);

    if (err.response?.data) {
      ctx.set('Content-Type', err.response.headers['content-type'] || 'text/plain');
      ctx.status = err.response.status;
      ctx.body = err.response.data;
    } else {
      ctx.status = 502;
      ctx.body = {
        error: "Dify服务不可用",
        details: err.message
      };
    }
  }
}

// 
router.post('/chat/chat-stream', async (ctx) => {
  const apiKey = 'Bearer app-A0qWUHGurE194dExw7vhi3SX';
  const body = ctx.request.body;
  const difyBody = { ...body, response_mode: "streaming" };
  await proxyStream(ctx, apiKey, difyBody);
});

// 教案设计
router.post('/chat/lesson-planning', async (ctx) => {
  const apiKey = 'Bearer app-A0qWUHGurE194dExw7vhi3SX';
  const body = ctx.request.body;
  const difyBody = { ...body, response_mode: "streaming" };
  await proxyStream(ctx, apiKey, difyBody);
});

// 试题解析
router.post('/chat/chat-analysis', async (ctx) => {
  const apiKey = 'Bearer app-zi7CT5UsYNpJqEZUAsJLGQmT';
  const body = ctx.request.body;
  const difyBody = { ...body, response_mode: "streaming" };
  await proxyStream(ctx, apiKey, difyBody);
});

module.exports = router;
